package com.cnpinxi.controller.admin.ueditor;

import com.baidu.ueditor.define.BaseState;
import com.baidu.ueditor.define.State;
import com.cnpinxi.controller.base.BaseController;
import com.cnpinxi.util.FileTools;
import com.cnpinxi.util.LoadPic;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

/**
 * Created by Baggio on 2017-10-11.
 *
 */
public class UeditorContorller extends BaseController {

public  static final String picPath="";
    public String upLoad(HttpServletRequest request, HttpServletResponse response) {
logger.info("ueditor===>>>upLoad");
        Map<String,String> map=super.showRequestParameters(request);
        FileItemStream fileStream = null;
        String filePath = FileTools.getUniquenessName("") + FileTools.PICTURE_SUFFIX_JPG;
        try {
            boolean isAjaxUpload = request.getHeader("X_Requested_With") != null;
            if(!ServletFileUpload.isMultipartContent(request)) {
                return new BaseState(false, 5).toJSONString();
            } else {
                ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
                if (isAjaxUpload) {
                    upload.setHeaderEncoding("UTF-8");
                }
                for (FileItemIterator e = upload.getItemIterator(request); e.hasNext(); fileStream = null) {
                    fileStream = e.next();
                    if (!fileStream.isFormField()) {
                        break;
                    }
                }

                if (fileStream == null) {
                    return new BaseState(false, 7).toJSONString();
                }
                InputStream is = fileStream.openStream();

                LoadPic.LoadPics(is,filePath);
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }catch (Exception e) {
            e.printStackTrace();
        }
        State storageState =  new BaseState(true);
        if(storageState.isSuccess()) {
            storageState.putInfo("url", picPath+"/pic/"+filePath);
            storageState.putInfo("type", FileTools.PICTURE_SUFFIX_JPG);
            storageState.putInfo("original",  filePath);
        }
        System.out.println("State===>>>/n"+storageState.toJSONString());
        return storageState.toJSONString();
    }


}